#include "widget.h"
#include "ui_widget.h"
#include <QUrlQuery>
#include <QNetworkReply>
#include <QCryptographicHash>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    client = new QNetworkAccessManager(this);
    connect(client, &QNetworkAccessManager::finished, this, &Widget::on_reply);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_transButton_clicked()
{
    QString src = ui->srcTextEdit->toPlainText();
    if (src.size() == 0)
    {
        return;
    }
    QString appid = "20191217000367019";
    QString secret = "GT1B4cylGQWyUQhvk6vs";
    QString salt = QTime::currentTime().toString();
    QString temp = appid + src + salt + secret;
    QString sign = QCryptographicHash::hash(temp.toUtf8(), QCryptographicHash::Md5).toHex();
    QString from = ui->srcComboBox->currentText();
    QString to = ui->dstComboBox->currentText();

    QUrlQuery params;
    params.addQueryItem("from", from);
    params.addQueryItem("to", to);
    params.addQueryItem("appid", appid);
    params.addQueryItem("salt", salt);
    params.addQueryItem("sign", sign);
    params.addQueryItem("q", src);

    QNetworkRequest request(QUrl("https://fanyi-api.baidu.com/api/trans/vip/translate"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
}

void Widget::on_reply(QNetworkReply* reply)
{
    ui->dstTextEdit->clear();

    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    if (json.contains("trans_result"))
    {
        QJsonArray results = json["trans_result"].toArray();
        for (int i = 0; i < results.size(); i++)
        {
            ui->dstTextEdit->appendPlainText(results[i].toObject()["dst"].toString());
        }
    }

    if (json.contains("error_code"))
    {
        QString error = "error:" + json["error_msg"].toString() + "(" + json["error_code"].toString() + ")";
        ui->dstTextEdit->appendPlainText(error);
    }

    reply->deleteLater();
}
